import {getStorage, getToken, UserKey} from "@/core/utils/storage";
import {resetRouter} from "@/core/router/router";
import {Route} from "vue-router";
import NProgress from "nprogress";
import {getDict} from "@/core/api/API";
import {SettingsModule} from "@/core/store/modules/settings";
import {constantPaths} from "@/core/router/router-const";

//微信登录路由
const loginPath = "/login";

//首页
const indexPath = "/weiXin/WxIndex";

//未登录时的放行路径 (未登录时，遇到这里的路径直接放行)
const noLoginPassPath = [loginPath];

//已登录时的放行路径 (已登陆后，遇到这里的路径直接放行)
const loginPassPath = [indexPath];

//已登录时的重定向路径 (登录后，遇到这里的路径直接重定向到根路由)
const loginRedirectPath = [loginPath];

export const weiXinHandler = async (to: Route, _: Route, next: any) => {
    let toPath = to.path;
    let oldPath = _.path;
    //console.log("toPath-->", toPath)
    //console.log("oldPath-->", oldPath)

    /**
     * 已登录
     */
    if (getToken()) {

        //检查界面是否执行了F5
        if (SettingsModule.refresh) {
            //console.log(1)
            await SettingsModule.SET_REFRESH(false);
            await getDict();
            next({...to, replace: false})
            return;
        }

        //检查是否需要重定向到根路由
        if (loginRedirectPath.indexOf(toPath) != -1) {
            //console.log(2)
            next(indexPath);
            return;
        }

        //直接放行
        if (loginPassPath.indexOf(toPath) != -1) {
            next();
            return;
        }

        //检查角色菜单
        // //console.log("constantPaths", constantPaths());
        // //console.log("getMenusPath", getMenusPath());
        // //console.log("hasRouter", hasRouter);
        let hasRouter = constantPaths().concat(getStorage(UserKey.MenusPath)).indexOf(toPath) != -1;
        if (!hasRouter) {
            next(indexPath);
            return;
        }

        //放行
        next();
    }

    /**
     * 未登录
     */
    else {
        //刷新
        resetRouter();

        //重定向到loginPath
        if (noLoginPassPath.indexOf(toPath) == -1) {
            next(`${loginPath}?redirect=${toPath}`);
            NProgress.done()
            return;
        }

        //直接放行
        next();
    }
};
